

#====================================================================
#
#		WEB RESPONSE OBJECT
#
#====================================================================

#--------------------------------------------------------------------
Function New-WebResponse
{
	param
	(
		  [psobject]			$WebRequest		= $null
		, [string]				$ResponseCode	= ""
		, [psobject]			$Resource		= ""
	)
	[psobject] $obj = New-Object psobject
	Add-Member -InputObject $obj -Force -MemberType NoteProperty -Name WebRequest	-Value $WebRequest
	Add-Member -InputObject $obj -Force -MemberType NoteProperty -Name ResponseCode	-Value $ResponseCode
	Add-Member -InputObject $obj -Force -MemberType NoteProperty -Name Resource		-Value $Resource
	return $obj
}


#--------------------------------------------------------------------
Function Send-WebResponseHeader
{
	param
	(
		  [psobject]	$WebResponse
	)

	# Construct the response header.
	[string] $Header = ""
	$Header += $WebResponse.WebRequest.Version
	$Header += " "
	$Header += $WebResponse.ResponseCode
	$Header += "`n"
	$Header += "Server: "
	$Header += $WebResponse.WebRequest.WebServer.ServerAddress
	$Header += "`n"
	$Header += "Accept-Ranges: bytes"
	$Header += "`n"
	if( $WebResponse.Resource -ne $null )
	{
		$Header += "Content-Type: "
		$Header += $WebResponse.Resource.Mime
		$Header += "`n"
		$Header += "Content-Length: "
		$Header += $WebResponse.Resource.Size
		$Header += "`n"
	}
	$Header += "`n"

	trap
	{
		Write-Error "`nError - $_"
		return $false
	}

	# Validate the socket.
	if( ($WebResponse.WebRequest.Socket -eq $null) `
		-or (-not $WebResponse.WebRequest.Socket.Connected) )
	{ return $false }

	# Send the response header.
	[byte[]] $HeaderBytes = AsciiString2Bytes $Header
	[int] $cbSent = $WebResponse.WebRequest.Socket.Send( $HeaderBytes )
    if ( $cbSent -eq -1 ) { return $false }

	# Return, OK
	return $true
}


#--------------------------------------------------------------------
Function Send-WebResponse
{
	param
	(
		  [psobject]	$WebResponse
		, [bool]		$SendHeader			= $true
	)
Write-Host $WebResponse.ResponseCode

	trap
	{
		Write-Error "`nError - $_"
		return $false
	}

	if( $SendHeader -eq $true )
	{
		# Send the response header.
		[bool] $b = Send-WebResponseHeader $WebResponse
		if( $b -eq $false ) { return $false }
	}

	# Send the resource content.
	if( $WebResponse.Resource -ne $null )
	{
		#Write-Debug -Message $Resource.Data
	    [int] $cbSent = $Socket.Send( $WebResponse.Resource.Data )
	    if ( $cbSent -eq -1 ) { return $false }
    }

	# Return, OK
	return $true
}

